package com.gupaoedu.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZKDemo {
    public static void main(String[] args) throws IOException {
        final   CountDownLatch downLatch = new CountDownLatch(1); //设置阻塞线程
        ZooKeeper zooKeeper = new ZooKeeper(
                "192.168.255.143:2181,"
                        + "192.168.255.141:2181," +
                        "192.168.255.142:2181", 4000,
                new Watcher() {
                    @Override
                    public void process(WatchedEvent watchedEvent) {
                        if (Event.KeeperState.SyncConnected==watchedEvent.getState()){//成功连接

                            downLatch.countDown(); //计数器减一
                        }
                    }
                }
        );

        try {
            downLatch.await();

            ZooKeeper.States state = zooKeeper.getState();
            System.out.println(state);




           /* zooKeeper.exists()*/

            zooKeeper.create("/wdt","http:192.168.1:8080".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            Thread.sleep(1000);
            Stat stat = new Stat();
            byte[] data2 = zooKeeper.getData("/wdt", null, stat);
            System.out.println(new String(data2));
            System.out.println(stat.getVersion());



            zooKeeper.setData("/wdt","1".getBytes(),stat.getVersion());
            byte[] data1 = zooKeeper.getData("/wdt", null, stat);
            System.out.println(new String(data1));
            System.out.println(stat.getVersion());

            zooKeeper.delete("/wdt",stat.getVersion());

            zooKeeper.close();

      //      System.in.read();  //阻塞当前线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }


    }
}
